using SqlSugar.IOC;
using Microsoft.Extensions.Configuration;
using IBaseService;
using BaseService;
using IBaseRepository;
using BaseRepository;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using System;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Blog.Profiles;
using System.Reflection;
using System.Runtime.Loader;
using Microsoft.Extensions.DependencyModel;
using Blog.Middleware;
using StackExchange.Redis;
using Blog.Utility.Redis;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();


#region swagger 添加 Authorize 授权认证
builder.Services.AddSwaggerGen(c => {
	c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
	{
		In = ParameterLocation.Header,
		Type = SecuritySchemeType.ApiKey,
		Description = "直接在下框输入Bearer{token}(注意两者之间是一个空格)",
		Name = "Authorization",
		BearerFormat = "JWT",
		Scheme = "Bearer"
	});

	c.AddSecurityRequirement(new OpenApiSecurityRequirement {
		{
			new OpenApiSecurityScheme
			{
				Reference = new OpenApiReference{
					Type = ReferenceType.SecurityScheme,
					Id = "Bearer"
				}
			},
			new string[] { }
		}
	});
	c.SwaggerDoc("v1", new OpenApiInfo { Title = "Blog API", Version = "v1" });
});

#endregion

//builder.Services.AddScoped<IArticleService, ArticleService>();
//builder.Services.AddScoped<IArticleRepository, ArticleRepository>();

//builder.Services.AddScoped<IArticleTypeService, ArticleTypeService>();
//builder.Services.AddScoped<IArticleTypeRepository, ArticleTypeRepository>();

//builder.Services.AddScoped<IAuthorService, AuthorService>();
//builder.Services.AddScoped<IAuthorRepository, AuthorRepository>();

//builder.Services.AddScoped<IRoleService, RoleService>();
//builder.Services.AddScoped<IRoleRepository, RoleRepository>();

//builder.Services.AddScoped<ICommentService, CommentService>();
//builder.Services.AddScoped<ICommentRepository, CommentRepository>();

//builder.Services.AddScoped<ILikeRelationService,LikeRelationService>();
//builder.Services.AddScoped<ILikeRelationRepository, LikeRelationRepository>();


#region redis注入服务
var redisConnectionString = builder.Configuration.GetConnectionString("Redis");
builder.Services.AddSingleton(new RedisConnecting(redisConnectionString));
#endregion



#region 注入产品服务 
var dependencyContext = DependencyContext.Default;
var assemblies = dependencyContext.RuntimeLibraries
	.Where(lib => lib.Name.Contains("Base"))
	.SelectMany(lib => lib.GetDefaultAssemblyNames(dependencyContext))//对每个筛选后的库，获取其默认的程序集名称。
	.Select(Assembly.Load)//根据程序集名称加载对应的程序集。
	.ToList();


var AssemblyList = assemblies.SelectMany(assembly => assembly.GetTypes());

var types = AssemblyList.Where(t => t.IsClass && !t.IsAbstract && t.Name.EndsWith("Service") || t.Name.EndsWith("Repository"))
			.Select(t => new
			{
				Service = t.GetInterfaces().FirstOrDefault(i => i.Name == "I" + t.Name),
				Implementation = t
			}).ToList();

foreach (var type in types)
{
	if (type.Service != null)
	{
		builder.Services.AddScoped(type.Service, type.Implementation);
	}
}
#endregion


#region  SqlSugar 服务注入
builder.Services.AddSqlSugar(new IocConfig()
{
    ConnectionString = builder.Configuration.GetConnectionString("SqlServer"),
    DbType = IocDbType.SqlServer,
    IsAutoCloseConnection = true //自动释放
});
#endregion


#region JWT 服务注入
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
	options.TokenValidationParameters = new TokenValidationParameters
	{
		ValidateIssuerSigningKey = true,
		IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("aBcD1234567890abCDefGHiJklMNOpQrStUvWxYz0987654321")),
		ValidateIssuer = true,
		ValidIssuer = "http://localhost/6060",
		ValidateAudience = true,
		ValidAudience = "http://localhost:7257",
		ValidateLifetime = true,
		ClockSkew = TimeSpan.FromMinutes(value: 60)
	};
});
#endregion


#region   AutoMap服务注入
builder.Services.AddAutoMapper(p =>
{
	p.AddProfile<AuthorMap>();//添加映射类
							  //p.AddMaps("WebNet6_Project");//遍历项目下集成Profile接口的类
});
#endregion


var app = builder.Build();





// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
	{
		c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
		//c.RoutePrefix = string.Empty; // Set the Swagger UI at the app's root
	});
}

app.UseHttpsRedirection();

//鉴权
app.UseAuthentication();

//自定义中间件
app.UseMiddleware<RequestLoggingMiddleware>();
//授权
app.UseAuthorization();



app.MapControllers();

app.Run();